package proguard.obfuscate;

import java.io.*;


/**
 * 修改了{@link MappingReader}的部分方法的可见性范围
 * 并提供了更多方便的方法
 */
public class MappingReaderExt extends MappingReader {

    public MappingReaderExt() {
        super(null);
    }

    /**
     * 请勿使用
     * @param mappingProcessor
     * @throws IOException
     */
    @Deprecated
    @Override
    public void pump(MappingProcessor mappingProcessor) throws IOException {
        throw new IOException("Deprecated!!! Do not use any more!!!");
    }

    public void pump(File mappingFile, MappingProcessor mappingProcessor) throws IOException {
        pump(new FileInputStream(mappingFile), mappingProcessor);
    }

    public void pump(InputStream mappingInputStream, MappingProcessor mappingProcessor) throws IOException {
        LineNumberReader reader =
                new LineNumberReader(
                        new BufferedReader(
                                new InputStreamReader(mappingInputStream, "UTF-8")));
        try {
            String[] className = new String[]{null};

            // Read the subsequent class mappings and class member mappings.
            while (true) {
                String line = reader.readLine();

                if (!pumpInternal(mappingProcessor, className, line)) break;
            }
        } catch (IOException ex) {
            throw new IOException("Can't process mapping file (" + ex.getMessage() + ")");
        } finally {
            try {
                reader.close();
            } catch (IOException ex) {
                // This shouldn't happen.
            }
        }
    }

    public void pump(String mappingString, MappingProcessor mappingProcessor) {
        String[] mappingStringLines = mappingString.split("\n");

        String[] className = new String[]{null};

        // Read the subsequent class mappings and class member mappings.

        for (int i = 0; i < mappingStringLines.length; i++) {

            String line = mappingStringLines[i];

            if (!pumpInternal(mappingProcessor, className, line)) break;
        }
    }

    private boolean pumpInternal(MappingProcessor mappingProcessor, String[] className, String line) {
        if (line == null) {
            return false;
        }

        line = line.trim();

        // Is it a non-comment line?
        if (!line.startsWith("#")) {
            // Is it a class mapping or a class member mapping?
            if (line.endsWith(":")) {
                // Process the class mapping and remember the class's
                // old name.
                className[0] = processClassMapping(line, mappingProcessor);
            } else if (className[0] != null) {
                // Process the class member mapping, in the context of
                // the current old class name.
                processClassMemberMapping(className[0], line, mappingProcessor);
            }
        }
        return true;
    }
}
